/* 
 * Modbus app for RTU.
 * Copyright (c) 2012  apleilx
 * All rights reserved.
 * no limite
 */

/* ----------------------- Platform includes --------------------------------*/
#define _MAPP_MODULE_
#include "mbapp.h"
#include "rtthread.h"

#define TEST_MODE MB_RTU_SLAVE

mb_baud_tab_create;

uint8_t mbTestErrCnt = 0;
uint8_t mbTestOkCnt = 0;

typedef struct
{
	uint16_t reg_r[64];
	uint16_t reg_w[64];
	uint16_t pv_r[64];
	uint16_t pv_w[64];
	uint16_t obj_size;
} mb_tst_type;

mb_tst_type mb_tst;

void rcv_end_handle_comp(uint8_t ErrSt);

/******************************************************************************
* @brief   	Slave device handle.
*               
* @param   none
*
* @return  none
*
* @ Pass/ Fail criteria: none
*****************************************************************************/
void modbus_task(const void *argv)
{
	mb_cmd_buff_type mcmd;

	mb_obj_init(&mb.obj07);
	
	//master config
	mb07_Init(MB_RTU_SLAVE, mb_baud_tab[MB_BAUD_115200], MB_PAR_NONE);
	mb.obj07.slave_id = 1;
	mb.obj07.rtu_master_delay_set = 3;
	mb.obj07.rcv_end_handle_comp = rcv_end_handle_comp;
	mb.obj07.os_event_send = mb_os_send;
	mb.obj07.os_event_base = 2 << 4;
	mb.obj07.rtu_len_cut = 1;

	//cmd config
	mcmd.device_id = 1;
	mcmd.cmd = FUN_CODE_READ_COILS;
	mcmd.dat = mb_tst.pv_w;
	mcmd.dat_addr = 0;
	mcmd.amount = 48;
	mcmd.call_back = 0;
	mb.obj07.api->stc_cmd_req(0, &mcmd);

	mcmd.cmd = FUN_CODE_READ_DISCRETE;
	mb.obj07.api->stc_cmd_req(1, &mcmd);

	mcmd.cmd = FUN_CODE_W_R_MULTIPLE_REG;
	mb.obj07.api->stc_cmd_req(2, &mcmd);

	mcmd.cmd = FUN_CODE_W_R_MULTIPLE_REG;
	mb.obj07.api->stc_cmd_req(3, &mcmd);

	mcmd.cmd = FUN_CODE_WRITE_MULTIPLE_REG;
	mb.obj07.api->stc_cmd_req(4, &mcmd);

	mcmd.cmd = FUN_CODE_WRITE_MULTIPLE_COIL;
	mb_tst.pv_w[0] = 0;
	mb.obj07.api->stc_cmd_req(5, &mcmd);

	//task handle
	for (;;)
	{
		int len;
		unsigned char buff[32];
		
		// wait modbus event
		rt_thread_delay(1);

		do
		{
			len = rt_device_read(rt_device_find("uart7"), -1, buff, 32);
			
			loop(len)
			{
				mb_data_rcv(&mb.obj07, buff[index]);
			}
			
		} while(len);
		
		mb_rtu_timer_run(&mb.obj07);

		if(mb.obj07.rcv_st == MB_RX_RCVEND)
		{
			mb.obj07.rtu_timer_cnt++;
		}
		
		mb_poll(&mb.obj07);
	}
}

void rcv_end_handle_comp(uint8_t ErrSt)
{
}
